/* eslint-disable array-callback-return,no-undef,guard-for-in,object-curly-newline,prefer-destructuring */
import React, { Component } from 'react';
import { Layout, Form, Spin, message, Tabs, Modal, Avatar } from 'antd';
import styles from '../../index.less';
import getConfigHigher from './baseHigher/getConfigHigher'; /*   获取配置   */
import getDataHigher from './baseHigher/getDataHigher'; /*   获取数据   */
import * as comFunc from '../Common/ComFunc'; /* 通用单据方法 */
import * as utils from '../../utils/utils'; /* 通用方法 */
import * as commonBusinessOld from './commonBusiness'; /* 单据业务功能 */
import * as commonBusiness from './business/commonBusiness'; /* 单据业务功能 */
import Toolbar from '../Common/ToolBar/ToolBarNew';
import TabMasterTable from './TabMasterTable';
import StaticEditTable from '../Common/StaticEditTable/StaticEditTableNew'; /* 可编辑表格 */
import ModalList from '../Common/ModalList/ModalList'; /* 弹窗表格 */
import * as config from '../../utils/config';

/*   业务   */
import * as buttonBusiness from './buttonBusiness/buttonBusiness'; /*   按钮业务   */
import * as toolbarBusiness from './buttonBusiness/toolbarBusiness'; /*   工具栏业务   */

const { Header, Content } = Layout;
const { TabPane } = Tabs;
const { confirm } = Modal;

class CommonBill extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ...props,
      selectedRowKeys: [], /*   已选择的数据行(数据格式:数组)   */
      delData: [], /*   已删除的数据集合,保存的时候会与从表一并传给服务器(数据格式:数组)   */
      expand: false, /* 默认主表只显示2行 */
      editTableRender: true, /* 表格是否渲染 */
      isNeedStatisticsTotal: false, /*   是否需要统计,不需要统计的话合计的时候就直接取后台传过来的数据(数据格式:布尔)   */
      imgSrc: '', /* Avatar组件中的img中src的资源路径 */
      currentIndexFlag: false, /* 默认不显示当前的数据在主表页的位置序号 */
      pageSize: config.pageSize, /* 列表页中一页的数据个数 */
      copyFrom: {}, /* 复制从弹窗配置及数据 */
      slaveTotal: [], /* 从表合计数据默认为空 */
    };
    this.masterSelectAllValue = {};/*   主表下拉数据集   */
    this.slaveSelectAllValue = {};/*   从表下拉数据集   */
    this.isMasterRender = {}; /* 主表控件是否渲染 */
    this.isSlaveRender = {}; /* 从表控件是否渲染 */
    this.isCheckRender = {}; /* 审核表控件是否渲染 */
    this.form = {}; /*   表单对象   */
    this.modalListVisible = false; /* 弹窗界面 */
  }

  componentWillReceiveProps(nextProps) {
    const { masterData } = this.state;
    const { isRender, isRenderPart } = nextProps;
    if (utils.isEmptyObject(masterData)) { /*   只有第一次渲染数据才走这里   */
      this.firstRenderData({ ...nextProps });
    } else if (isRender) { /*   需要从高阶重新渲染数据的走这里   */
      this.higherRenderData({ ...nextProps });
    } else if (isRenderPart) { /*   不从高阶里面带入数据并且还要渲染的走这里   */
      this.selfRenderData({ ...nextProps });
    }
  }

  componentDidUpdate() {
    /* 界面伸缩时需要用到,因为此方法用不了setState,所以用了this */
    const { masterShowConfig, slaveShowConfig, slaveData, checkShowConfig, checkData } = this.state;
    this.resetRender(masterShowConfig, slaveShowConfig, slaveData, checkShowConfig, checkData);
  }

  // ----------------------------生命周期start---------------------------- //
  /*   第一次渲染数据   */
  firstRenderData = (props) => {
    /*   避免切换页签时，数据被高阶数据替换掉   */
    const { masterShowConfig, sId, slaveShowConfig, slaveData, checkShowConfig, checkData, copyToData } = props;
    /*   首次全渲染   */
    this.allRender(masterShowConfig, slaveShowConfig, slaveData, checkShowConfig, checkData);
    /*   再赋值高阶数据   */
    this.setState({ ...props });
    /*   存在sid那就说明不是新增数据,是查看数据,存在copyToData是复制到数据,这两种情况是需要走查看业务的   */
    if (sId !== '' || utils.isNotEmptyObject(copyToData)) {
      this.handleView(props);
    }
  };

  /**   查看数据时，获取其它值   */
  handleView = async (props) => {
    /*   窗体编号(本页面的唯一标示)   */
    const { masterConfig } = props;
    const { sModelType } = masterConfig;
    /*   查看单据时需要执行的业务   */
    props = commonBusiness.handleView(props);
    /*   修改state   */
    this.saveReturnData(props);
    /*   销售业务需要处理到期应收应付   */
    if (sModelType.startsWith('sales')) {
      await this.handleOutData(props);
    }
  };

  /*   高阶渲染数据   */
  higherRenderData = (props) => {
    /*   待用数据声明   */
    const { masterShowConfig, slaveShowConfig, checkShowConfig, checkData, isChangeHandleTypeUpdate, dataTotal, slaveData } = props;
    /*   重置handleType状态   */
    if (isChangeHandleTypeUpdate) {
      props = commonBusiness.addSlaveDataHandleType(props);
    }
    /*   添加合计   */
    props.slaveTotal = comFunc.addDataTotal(slaveShowConfig, dataTotal, slaveData, true);
    /*   渲染处理   */
    this.allRenderAndSetState(masterShowConfig, slaveShowConfig, slaveData, checkShowConfig, checkData, props);
  };

  /*   本页面渲染数据   */
  selfRenderData = (props) => {
    /*   待用数据声明   */
    const { masterShowConfig, slaveShowConfig, checkShowConfig, editTableRender } = props;
    const { slaveData, checkData } = this.state;
    let { showRender, showSlaveRender } = props;
    showRender = utils.isEmptyArr(showRender) ? [] : showRender;
    showSlaveRender = utils.isEmptyObject(showSlaveRender) ? [] : showSlaveRender;
    /*   数据渲染   */
    this.dataRenderAndSetState(
      masterShowConfig,
      showRender,
      slaveShowConfig,
      slaveData,
      showSlaveRender,
      checkShowConfig,
      checkData,
      editTableRender,
    );
  };
  // ----------------------------生命周期end  ---------------------------- //

  // ----------------------------销售模块异步start---------------------------- //
  handleSalesManage = async (props) => {
    const key = commonBusinessOld.getChangeSName(props);
    if (key === 'sCustomerId') {
      await this.handleOutData(props);
    }
  };

  /** 获取应收，到期应收 */
  handleOutData = async (props) => {
    /*   外置业务   */
    props = await commonBusiness.getOutData(props);
    /*   业务执行成功才执行渲染   */
    if (utils.isNotUndefined(props)) {
      /*   数据回带赋值   */
      this.saveReturnData(props);
    }
  };
  // ----------------------------销售模块异步end---------------------------- //

  // ----------------------------按钮 start---------------------------- //
  /**   添加从表空行   */
  handleAddSlaveRow = () => {
    /*   外置处理业务   */
    const props = buttonBusiness.handleAddSlaveRow({
      ...this.props,
      ...this.state,
      message,
    });
    /*   数据回带赋值   */
    this.saveReturnData(props);
  };

  /**   删除从表行   */
  handleDelSlaveRow = () => {
    /*   外置处理业务   */
    const props = buttonBusiness.handleDelSlaveRow({
      ...this.props,
      ...this.state,
      message,
    });
    /*   数据回带赋值   */
    this.saveReturnData(props);
  };

  /**   处理选择行发生改变   */
  handleSelectRowChange = (selectedRowKeys) => {
    /*   外置处理业务   */
    const props = buttonBusiness.handleSelectRowChange({
      ...this.props,
      ...this.state,
      selectedRowKeys,
    });
    /*   数据回带赋值   */
    this.saveReturnData(props);
  };
  // ----------------------------按钮 end---------------------------- //

  // ----------------------------toolbar start---------------------------- //
  /**   新增   */
  handleAdd = (obj) => {
    /*   外置处理业务   */
    const props = toolbarBusiness.handleAdd({
      ...this.props,
      ...this.state,
      ...obj,
    });
    /*   数据回带赋值   */
    this.saveReturnData(props);
  };

  /**   修改   */
  handleEdit = (obj) => {
    /*   外置处理业务   */
    const props = toolbarBusiness.handleEdit({
      ...this.props,
      ...this.state,
      ...obj,
    });
    /*   数据回带赋值   */
    this.saveReturnData(props);
  };

  /* 删除 */
  handleDel = (obj) => {
    /*   外置处理业务   */
    toolbarBusiness.handleDel({
      ...this.props,
      ...this.state,
      ...obj,
      confirm,
    });
  };

  /**   保存   */
  handleSave = async () => {
    /*   外置处理业务   */
    const props = toolbarBusiness.handleSaveValidate({
      ...this.props,
      ...this.state,
      isMasterRender: this.isMasterRender,
      message,
    });
    /*   判断验证是否通过   */
    if (utils.isNotEmptyStr(props.saveError)) { /*   验证未通过   */
      message.warning(props.saveError);
    } else { /*   验证通过继续验证表单   */
      /*   表单验证   */
      this.validateForm(props);
    }
  };

  /*   保存验证表单   */
  validateForm = (props) => {
    /*   验证一下   */
    this.form.validateFieldsAndScroll((err) => {
      /*   验证通过与不通过走不同的流程   */
      if (err) { /*   验证失败   */
        /*   直接渲染显示错误提示   */
        for (const key of Object.keys(err)) {
          props.isMasterRender[key] = true;
          props.message.warning(err[key].errors[0].message);
        }
      } else { /*   验证成功   */
        /*   设置页面不可用   */
        this.setState({ pageLoading: true });
        /*   保存数据   */
        toolbarBusiness.handleSaveData(props).then((resProps) => {
          /*   回带数据赋值   */
          this.saveReturnData(resProps);
        });
      }
    });
  };

  /*   取消  */
  handleCancel = () => {
    /*   外置处理业务   */
    toolbarBusiness.handleCancel({
      ...this.props,
      ...this.state,
    });
  };

  /*  上一条、下一条、首条、末条 */
  handleSearchData = async (handleType) => {
    /*   外置处理业务   */
    const props = await toolbarBusiness.handleSearchData({
      ...this.props,
      ...this.state,
      handleType,
    });
    /*   数据回带赋值   */
    if (utils.isNotUndefined(props)) {
      this.saveReturnData(props);
    }
  };

  /*   上查下查三级菜单   */
  handleSearchUpDownThird = async (upDownKey) => {
    /*   外置处理业务   */
    const props = await toolbarBusiness.handleSearchUpDownThird({
      ...this.props,
      ...this.state,
      upDownKey,
      message,
    });
    /*   数据回带赋值   */
    if (utils.isNotUndefined(props)) {
      this.saveReturnData(props);
    }
  };

  /*   单据页上查下查跳转页面   */
  handleSearchUpDown = async (sId, sActiveId) => {
    /*   外置处理业务   */
    toolbarBusiness.handleSearchUpDown({
      ...this.props,
      ...this.state,
      upDownSid: sId,
      upDownSActiveId: sActiveId,
    });
  };

  /**   审核(消审)   */
  handleAudit = async (flag) => {
    /*   外置处理业务   */
    const props = await toolbarBusiness.handleAudit({
      ...this.props,
      ...this.state,
      auditFlag: flag,
      message,
    });
    /*   数据回带赋值   */
    if (utils.isNotUndefined(props)) {
      this.saveReturnData(props);
    }
  };

  /*   单据页复制到   */
  handleCopyTo = (sActiveId, masterAssign, slaveAssign) => {
    /*   外置处理业务   */
    toolbarBusiness.handleBillCopyTo({
      ...this.props,
      ...this.state,
      masterAssign,
      slaveAssign,
      copyToSActiveId: sActiveId,
    });
  };

  /*   单据页复制从   */
  handleCopyFrom = async (obj) => {
    this.modalListVisible = true;
    const props = await toolbarBusiness.handleBillCopyFrom({
      ...this.props,
      ...this.state,
      ...obj,
    });
    /*   数据回带赋值   */
    if (utils.isNotUndefined(props)) {
      this.saveReturnData(props);
    }
  };

  /* 作废、取消作废的公用函数 */
  handleInvalid = (obj) => {
    /*   待用数据声明   */
    const props = {
      ...this.props,
      ...this.state,
      message,
      invalidhandleType: obj.handleType,
    };
    const saveReturnData = this.saveReturnData;
    /*   确认作废   */
    confirm({
      title: obj.title,
      onOk() {
        /*   外置处理业务   */
        toolbarBusiness.handleOkChangeInvaild(props).then((resProps) => {
          /*   数据回带赋值   */
          if (utils.isNotUndefined(resProps)) {
            saveReturnData(resProps);
          }
        });
      },
      onCancel() {
      },
    });
  };

  /*   打印   */
  handlePrint = (dataSid) => {
    /*   外置处理业务   */
    toolbarBusiness.handlePrint({
      ...this.props,
      ...this.state,
      printSid: dataSid,
    });
  };
  // ----------------------------toolbar end  ---------------------------- //

  // ----------------------------页面功能函数start---------------------------- //
  /**   全不渲染   */
  allDisRender = (masterShowConfig, slaveShowConfig, slaveData, checkShowConfig, checkData) => {
    this.isMasterRender = comFunc.setMasterRenderTrueOrFalse(masterShowConfig, false);
    this.isSlaveRender = comFunc.setSlaveRenderTrueOrFalse(slaveShowConfig, slaveData, false);
    this.isCheckRender = comFunc.setSlaveRenderTrueOrFalse(checkShowConfig, checkData, false);
    this.setState({ editTableRender: false });
  };

  /**   充值渲染渲染   */
  resetRender = (masterShowConfig, slaveShowConfig, slaveData, checkShowConfig, checkData) => {
    this.isMasterRender = comFunc.setMasterRenderTrueOrFalse(masterShowConfig, false);
    this.isSlaveRender = comFunc.setSlaveRenderTrueOrFalse(slaveShowConfig, slaveData, false);
    this.isCheckRender = comFunc.setSlaveRenderTrueOrFalse(checkShowConfig, checkData, false);
    this.modalListVisible = false;
  };

  /**   全渲染   */
  allRender = (masterShowConfig, slaveShowConfig, slaveData, checkShowConfig, checkData) => {
    this.isMasterRender = comFunc.setMasterRenderTrueOrFalse(masterShowConfig, true);
    this.isSlaveRender = comFunc.setSlaveRenderTrueOrFalse(slaveShowConfig, slaveData, true);
    this.isCheckRender = comFunc.setSlaveRenderTrueOrFalse(checkShowConfig, checkData, true);
    this.setState({ editTableRender: true });
  };

  /**   全渲染并setState   */
  allRenderAndSetState = (masterShowConfig, slaveShowConfig, slaveData, checkShowConfig, checkData, stateData) => {
    this.isMasterRender = comFunc.setMasterRenderTrueOrFalse(masterShowConfig, true);
    this.isSlaveRender = comFunc.setSlaveRenderTrueOrFalse(slaveShowConfig, slaveData, true);
    this.isCheckRender = comFunc.setSlaveRenderTrueOrFalse(checkShowConfig, checkData, true);
    if (utils.isEmptyObject(stateData)) {
      this.setState({ editTableRender: true });
    } else {
      this.setState({ ...stateData, editTableRender: true });
    }
  };

  /**   数据渲染并setState   */
  dataRenderAndSetState = (masterShowConfig, masterShowRender, slaveShowConfig, slaveData, slaveShowRender, checkShowConfig, checkData, editTableRender, stateData) => {
    this.isMasterRender = comFunc.setMasterRender(masterShowConfig, masterShowRender);
    this.isSlaveRender = comFunc.setSlaveCellRender(slaveShowConfig, slaveData, slaveShowRender);
    this.isCheckRender = comFunc.setSlaveRenderTrueOrFalse(checkShowConfig, checkData, false);
    if (utils.isEmptyObject(stateData)) {
      this.setState({ editTableRender: utils.converStrToBoolean(editTableRender) });
    } else {
      this.setState({ ...stateData, editTableRender: utils.converStrToBoolean(editTableRender) });
    }
  };

  /**   回带数据赋值   */
  saveReturnData = (props) => {
    this.isMasterRender = props.isMasterRender;
    this.isSlaveRender = props.isSlaveRender;
    this.isCheckRender = props.isCheckRender;
    this.setState({ ...props });
  };

  /**   表单回带   */
  handleForm = (form) => {
    this.form = form;
  };

  /** 主表控件是否全部显示 */
  handleToggle = () => {
    const { expand } = this.state;
    this.setState({ expand: !expand, editTableRender: false });
  };
  // ----------------------------页面功能函数end ---------------------------- //

  // ----------------------------下拉回带start---------------------------- //
  /**   回带主表下拉数据   */
  handleReturnMasterSelectValue = (sName, valueArr) => {
    this.masterSelectAllValue[sName] = valueArr;
  };

  /**   回带从表下拉数据   */
  handleReturnSlaveSelectValue = (sName, valueArr, sSlaveId) => {
    const obj = utils.convertUndefinedToEmptyObject(this.slaveSelectAllValue[sSlaveId]);
    obj[sName] = valueArr;
    this.slaveSelectAllValue[sSlaveId] = obj;
  };
  // ----------------------------下拉回带end  ---------------------------- //

  // ----------------------------数据修改回带start---------------------------- //
  /**   修改主表数据   */
  handleMasterChange = (changeValue) => {
    /*   待用数据赋值   */
    let { masterData } = this.state;
    masterData = { ...masterData, ...changeValue };
    /*   参数赋值   */
    const props = {
      ...this.state,
      changeValue,
      masterData,
      masterSelectAllValue: this.masterSelectAllValue,
      slaveSelectAllValue: this.slaveSelectAllValue,
    };
    /*   主表数据特殊处理   */
    this.handleMasterSpecial(props);
  };

  /**   主表数据特殊处理   */
  handleMasterSpecial = async (props) => {
    /*   特殊处理   */
    props = commonBusiness.handleMasterSpecial(props);
    /*   渲染数据   */
    this.saveReturnData(props);
    /*   长时间的数据处理   */
    const { masterConfig } = props;
    const { sModelType } = masterConfig;
    if (sModelType.startsWith('sales')) {
      await this.handleSalesManage(props);
    }
  };

  /** 从表数据更改 */
  handleSlaveChange = (changeValue, sSlaveId) => {
    const props = {
      ...this.state,
      changeValue,
      sSlaveId,
      isSlaveRender: this.isSlaveRender,
      masterSelectAllValue: this.masterSelectAllValue,
      slaveSelectAllValue: this.slaveSelectAllValue,
    };
    this.handleSalveChangeProps(props);
  };

  /** 修改从表时，具体操作 */
  handleSalveChangeProps = async (props) => {
    props = commonBusiness.handleSlaveChange(props);
    this.saveReturnData(props);
  };

  /** 复制从弹窗数据回带 */
  handleListData = (data) => {
    const { slaveData } = this.state;
    const slaveNotTotalData = slaveData.filter(item => !item.dataTotal);
    const slaveTotalData = slaveData.filter(item => item.dataTotal);
    this.modalListVisible = false;
    this.setState({
      slaveData: [...slaveNotTotalData, ...data, ...slaveTotalData],
      editTableRender: true,
    });
  };

  // ----------------------------数据修改回带end  ---------------------------- //

  render() {
    const { pageLoading } = this.state;
    const { imgSrc } = commonBusinessOld.handleAddIcon({ ...this.props, ...this.state });
    return (
      <div>
        <Spin spinning={pageLoading}>
          <div>
            <BillComponent
              {...this.props}
              {...this.state}
              onMasterChange={this.handleMasterChange}
              onReturnMasterSelectValue={this.handleReturnMasterSelectValue}
              onReturnSlaveSelectValue={this.handleReturnSlaveSelectValue}
              onToggle={this.handleToggle}
              onAdd={this.handleAdd}
              onEdit={this.handleEdit}
              onSubmit={this.handleSave}
              isMasterRender={this.isMasterRender}
              isSlaveRender={this.isSlaveRender}
              isCheckRender={this.isCheckRender}
              onAddRow={this.handleAddSlaveRow}
              onDelRow={this.handleDelSlaveRow}
              onSelectRowChange={this.handleSelectRowChange}
              onSlaveChange={this.handleSlaveChange}
              onReturnForm={this.handleForm}
              onChangeInvalid={this.handleInvalid}
              onBtnExamine={this.handleAudit.bind(this, 1)}
              onBtnCancelExamine={this.handleAudit.bind(this, 0)}
              onCopyTo={this.handleCopyTo}
              onCopyFrom={this.handleCopyFrom}
              onSearchUpDown={this.handleSearchUpDown}
              onSearchUpDownThird={this.handleSearchUpDownThird}
              onNext={this.handleSearchData.bind(this, 'next')}
              onBtnPrior={this.handleSearchData.bind(this, 'up')}
              onBtnFirst={this.handleSearchData.bind(this, 'first')}
              onBtnLast={this.handleSearchData.bind(this, 'end')}
              onCancel={this.handleCancel}
              onBtnPrint={this.handlePrint}
              onDel={this.handleDel}
              imgSrc={imgSrc}
            />
            <ModalList
              modalListVisible={this.modalListVisible}
              modalListData={this.state.copyFrom}
              onModalListData={this.handleListData}
            />
          </div>
        </Spin>
      </div>
    );
  }
}

const BillComponent = Form.create({
  mapPropsToFields(props) {
    const { masterData } = props;
    const obj = comFunc.mapPropsToFields(masterData, Form);
    return obj;
  },
})((props) => {
  const { form, onReturnForm } = props;
  /*   回带表单   */
  onReturnForm(form);
  const slaveProps = {
    ...props,
    headerColumn: props.slaveColumn,
    config: props.slaveConfig,
    data: props.slaveData,
    isRender: props.editTableRender,
    isShowTypeRender: props.isSlaveRender,
    totalData: props.slaveTotal,
  };
  const checkProps = {
    ...props,
    headerColumn: props.checkColumn,
    config: props.checkConfig,
    data: props.checkData,
    isRender: props.editTableRender,
    isShowTypeRender: props.isCheckRender,
    totalData: [],
  };
  return (
    <Form>
      <Layout>
        <Header className={styles.header}>
          <Toolbar {...props} />
        </Header>
        <Layout className={styles.clayout}>
          <Content className={styles.content}>
            <TabMasterTable {...props} />
            <div id="slaveTabs" className={styles.bShow}>
              <div>
                <Avatar src={props.imgSrc} />
              </div>
              <Tabs className={styles.slaveTabs}>
                <TabPane tab="主体内容" key={2}>
                  <StaticEditTable {...slaveProps} abble="1" />
                </TabPane>
                <TabPane tab="审批信息" key={3}>
                  <StaticEditTable {...checkProps} abble="2" />
                </TabPane>
              </Tabs>
            </div>
          </Content>
        </Layout>
      </Layout>
    </Form>
  );
});

export default getConfigHigher(getDataHigher(CommonBill));

